package com.rectcircle.scalatrateset.controller

import java.io.File

import org.scalatra.{BadRequest, Ok, RequestEntityTooLarge}
import org.scalatra.servlet.{FileItem, FileUploadSupport, MultipartConfig, SizeConstraintExceededException}


/**
  * @author Rectcircle
  *         createTime 2017/1/4
  */
class UploadController extends ScalatratestStack with FileUploadSupport {
	//配置最大上传文件大小
	configureMultipartHandling(MultipartConfig(maxFileSize = Some(3*1024*1024)))
	
	get("/") {
		<html>
			<body>
				<form action="/upload" method="post" enctype="multipart/form-data">
					<input type="file" name="file" />
					<input type="submit" name="upload"/>
				</form>
				<p>使用上述表单上传文件。点击“上传”后 该文件将被上传，您的浏览器将开始 下载它。</p>
				<p>接受的最大文件大小为3 MB。</p>
			</body>
		</html>
	}
	
	
	post("/") {
		fileParams.get("file") match {
			case Some(file) =>
				
				file.write(new File("D:/Test/"+file.name))
//				println(file.name)
//				Ok(file.get(), Map(
//					"Content-Type"        -> (file.contentType.getOrElse("application/octet-stream")),
//					"Content-Disposition" -> ("attachment; filename=\"" + file.name + "\"")
//				))
				<p>上传成功</p>
			
			case None =>
				BadRequest(
					<p>
						Hey! You forgot to select a file.
					</p>
				)
		}
	}
	
	error {
		case e: SizeConstraintExceededException => RequestEntityTooLarge("too much!")
	}
	
}
